Foreach loop

For each (or foreach) is a computer language idiom for traversing items in a collection. Foreach is usually used in place of a standard for statement. Unlike other for loop constructs, however, foreach loops [1] usually maintain no explicit counter: they essentially say "do this to everything in this set", rather than "do this x times". This avoids potential off-by-one errors and makes code simpler to read. In object-oriented languages an iterator, even if implicit, is often used as the means of traversal.

Contents

Syntax

Syntax varies among languages. Most use the simple word for, roughly as follows:

for each item in collection:
  do something to item

Language support

Some of the languages with support for foreach loops include ABC, ActionScript, Ada, C++11, C#, Cobra, D, ECMAScript, Java (since 1.5), JavaScript, Objective-C (since 2.0), Perl, PHP, Python, REALbasic, Ruby, Smalltalk, Tcl, tcsh, Daplex (a query language), Unix shells, Visual Basic .NET and Windows PowerShell. Notable languages without foreach are C and C++ (prior to C++11).

ActionScript

ActionScript supports foreach loops by key/index and by value:

for ( var key:String in someObject ) {
   var value = someObject[key];
   trace( "someObject[" + key + "] = " + someObject[key] );
}
 
for each ( var value in someArray ) {
   trace( typeof value + " " + value );
}
Note
someArray could be any object and someObject could be an array, but typical usage is as shown.

Ada

Ada supports foreach loops as part of the normal for loop. Say X is an array:

for I in X'Range loop
   X (I) := Get_Next_Element;
end loop;
Note
This syntax is mostly used on arrays but will also work with other types when a full iteration is needed.

C#

Assuming that myArray is an array of integers:

foreach (int x in myArray)
{
  Console.WriteLine(x);
}

C++

C++11 provides a for each loop. The syntax is taken from Java and looks like this:

#include <iostream>
int main()
{
  int myint[] = {1,2,3,4,5};
 
  for (int& i: myint)
  {
    std::cout << i << std::endl;
  }
}

Currently, C++11 range-based for statements have been implemented in GCC (since version 4.6) and clang (since version 3.0).

Qt, a C++ framework, offers a macro providing foreach loops[2] using the STL iterator interface:

#include <QList>
#include <QDebug>
 
int main() {
        QList<int> list;
        list << 1 << 2 << 3 << 4 << 5;
        foreach (int i, list) {
                qDebug() << i;
        }
}

Objective-C

Foreach loops, called Fast enumeration, are supported starting in Objective-C 2.0. They can be used to iterate over any object that implements the NSFastEnumeration protocol, including NSArray, NSDictionary (iterates over keys), NSSet, etc.

NSArray *a = [NSArray new];       // Any container class can be substituted
 
for(id obj in a) {                // Note the dynamic typing (we do not need to know the
                                  // Type of object stored in 'a'.  In fact, there can be
                                  // many different types of object in the array.
 
    printf("%s\n", [[obj description] UTF8String]);  // Must use UTF8String with %s
    NSLog(@"%@", obj);                               // Leave as an object
}

NSArrays can also broadcast a message to their members:

NSArray *a = [NSArray new];
 
[a makeObjectsPerformSelector:@selector(printDescription)];

Where blocks are available, an NSArray can automatically perform a block on every contained item:

[myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
	{
		NSLog(@"obj %@", obj);
		if ([obj shouldStopIterationNow])
			*stop = YES;
	}];

The type of collection being iterated will dictate the item returned with each iteration. For example:

NSDictionary *d = [NSDictionary new];
 
for(id key in d) {
    NSObject *obj = [d objectForKey:key];      // We use the (unique) key to access the (possibly non-unique) object.
    NSLog(@"%@", obj);
}

D

foreach(item; set) {
  // do something to item
}
or
foreach(argument) {
  // pass value
}

Delphi

Foreach support was added in Delphi 2005, and uses an enumerator variable that must be declared in the var section.

for enumerator in collection do
begin
  //do something here
end;

Eiffel

The iteration (foreach) form of the Eiffel loop construct is introduced by the keyword across.

In this example, every element of the structure my_list is printed:

            across my_list as ic loop print (ic.item) end

The local entity ic is an instance of the library class ITERATION_CURSOR. The cursor's feature item provides access to each structure element. Descendants of class ITERATION_CURSOR can be created to handle specialized iteration algorithms. The types of objects that can be iterated across (my_list in the example) are based on classes that inherit from the library class ITERABLE.

The iteration form of the Eiffel loop can also be used as a boolean expression when the keyword loop is replaced by either all (effecting universal quantification) or some (effecting existential quantification).

This iteration is a boolean expression which is true if all items in my_list have counts greater than three:

            across my_list as ic all ic.item.count > 3 end

The following is true if at least one item has a count greater than three:

            across my_list as ic some ic.item.count > 3 end

Go

Go's foreach loop can be used to loop over an array, slice, string, map, or channel.

Using the two-value form, we get the index/key (first element) and the value (second element):

for index, value := range someCollection {
  // do something to index and value
}

Using the one-value form, we get the index/key (first element):

for index := range someCollection {
  // do something to index
}

[1]

Groovy

Groovy supports for loops over collections like arrays, lists and ranges:

def x = [1,2,3,4]
for (v in x)           // loop over the 4-element array x
{
    println v
}
 
for (v in [1,2,3,4])   // loop over 4-element literal list 
{
    println v
}
 
for (v in 1..4)        // loop over the range 1..4
{
    println v
}

Groovy also supports a C-style for loop with an array index:

for (i = 0; i < x.size(); i++)
{
    println x[i]
}

Collections in Groovy can also be iterated over using the each keyword and a closure. By default, the loop dummy is named it

x.each{ println it }     // print every element of the x array
x.each{i-> println i}    // equivalent to line above, only loop dummy explicitly named "i"

Haskell

mapM_ someFunction someList

haXe

for (value in iterable) {
    trace(value);
}
 
Lambda.iter(iterable, function(value) trace(value));

Java

A foreach-construct was introduced in JDK 1.5.0.[3] Official sources use several names for the construct. It is referred to as the "Enhanced for Loop"[3] the "For-Each Loop"[4] and the "foreach statement".[5]

for (type item: set) {
  // do something to item
}

JavaScript

For unordered iteration over the keys in an Object, JavaScript features the for...in loop:

for (var key in object) {
    //do stuff with object[key]
}

In order to limit the iteration to the object's own properties, excluding the ones inherited through the prototype chain, it is sometimes useful to add a hasOwnProperty() test, if supported by the JavaScript engine (for WebKit/Safari, this means "in version 3 or later").

for (var key in object) {
    if (object.hasOwnProperty(key)) {
        //do stuff with object[key]
    }
}

Gecko’s JavaScript engine also has a for each...in statement, which iterates over the values in the object, not the keys.[6]

Also note that it is inadvisable to use either a for...in or for each...in statement on an Array object in JavaScript, due to the above issue of properties inherited from prototypes, and also because it only iterates over existent keys and is not guaranteed to iterate over the elements in any particular order.[7] A regular C-style for loop should be used instead.

Ocaml

Since Ocaml is a functional language, the equivalent of a foreach loop can be achieved as a library function over lists and arrays.

For Lists :

List.iter (fun x -> print_int x) [1;2;3;4];;

or in short way :

List.iter print_int [1;2;3;4];;

For Arrays :

Array.iter (fun x -> print_int x) [|1;2;3;4|];;

or in short way :

Array.iter print_int [|1;2;3;4|];;

Pascal

The ISO 10206:1990 standard introduced iteration over set types in Pascal:

var
  elt: ElementType;
  eltset: set of ElementType;
 
{...}
 
for elt in eltset do
  { ... do something with elt }

Perl

In Perl, foreach (which is equivalent to the shorter for) can be used to traverse elements of a list. The expression which denotes the collection to loop over is evaluated in list-context and each item of the resulting list is, in turn, aliased to the loop variable.

List literal example:

foreach (1, 2, 3, 4) {
    print $_;
}

Array examples:

foreach (@arr) {
    print $_;
}
foreach $x (@arr) { #$x is the element in @arr
    print $x;
}

Hash example:

foreach $x (keys %hash) {
    print $x . " = " . $hash{$x}; # $x is a key in %hash and $hash{$x} is its value
}

Direct modification of collection members:

@arr = ( 'remove-foo', 'remove-bar' );
foreach $x (@arr){
    $x =~ s/remove-//;
}
# Now @arr = ('foo', 'bar');

PHP

PHP has an idiosyncratic syntax:

 
foreach($set as $value)
{
  // do something to $value;
}

It is also possible to extract both keys and values using the alternate syntax:

foreach ($set as $key => $value) {
  echo "{$key} has a value of {$value}";
}

Direct modification of collection members:

$arr = array(1, 2, 3);
foreach ($set as &$value) { // note the &, $value is a reference to the original value inside $set
  $value++;
}
// Now $arr = array(2, 3, 4);
 
// also works with the full syntax
foreach ($set as $key => &$value) {
  $value++;
}

Python

for item in iterable_collection:
  # do something with item

Python's tuple assignment, fully available in its foreach loop, also makes it trivial to iterate on (key, value) pairs in associative arrays:

for key, value in some_dict.items(): # direct iteration on a dict iterates on its keys
    # do stuff

As for...in is the only kind of for loop in Python, the equivalent to the "counter" loop found in other languages is...

for i in range(len(seq)):
    # do something to seq[i]

... though using the enumerate function is considered more "Pythonic":

for i, item in enumerate(seq):
    # do stuff with item
    # possibly assign it back to seq[i]

Ruby

set.each do |item|
  # do something to item
end

or

for item in set
  # do something to item
end

You can also use this with a hash.

set.each do |item,value|
  # do something to item
  # do something to value
end

Racket

 

or using the conventional Scheme for-each function:

 

Smalltalk

collection do: [|item| # do something to item ]

Tcl

Tcl uses foreach to iterate over lists. It is possible to specify more than one iterator variable, in which case they are assigned sequential values from the list. The code below prints:
1 2
3 4
5 6

foreach {i j} {1 2 3 4 5 6} {
   puts "$i $j"
}

It is also possible to iterate over more than one list simultaneously. In the following i assumes sequential values of the first list, j sequential values of the second list:

foreach i {1 2 3} j {a b c}  {
   puts "$i $j"
}

This prints:
1 a
2 b
3 c

Visual Basic .NET

For Each item As type In set
 ' do something to item
Next item

Windows PowerShell

foreach ($item in $set) {
  # do something to $item
}

XSL

[8]

<xsl:for-each select="set">
  <!-- do something for the elements in <set> -->
</xsl:for-each>

See also

References